<template>
  <CloudDialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit">
    <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
      <a-form-item
        label="账户名称"
        field="name"
        hide-asterisk
        asterisk-position="end">
        <a-input
          v-model="formState.name"
          :max-length="20"
          show-word-limit
          placeholder="请输入账户名称" />
      </a-form-item>
      <a-form-item
        label="DNS 服务商"
        field="provider"
        class="server-item"
        hide-asterisk
        asterisk-position="end">
        <a-select
          v-model="formState.provider"
          :options="providerOptions"
          placeholder="请选择 DNS 服务商"></a-select>
      </a-form-item>
      <!-- cloudflare -->
      <a-form-item
        v-if="formState.provider === 2"
        label="API Token"
        field="provider_config.api_token"
        hide-asterisk
        asterisk-position="end">
        <a-input
          v-model="formState.provider_config.api_token"
          placeholder="请输入 API Token" />
      </a-form-item>
      <!-- aliyun -->
      <section v-else-if="formState.provider === 3">
        <a-form-item
          label="AccessKey ID"
          field="provider_config.access_key_id"
          hide-asterisk>
          <a-input
            v-model.trim="formState.provider_config.access_key_id"
            placeholder="请输入 AccessKey ID"></a-input>
        </a-form-item>
        <a-form-item
          label="AccessKey Secret"
          field="provider_config.access_key_secret"
          hide-asterisk>
          <a-input
            v-model.trim="formState.provider_config.access_key_secret"
            placeholder="请输入 AccessKey Secret"></a-input>
        </a-form-item>
      </section>
      <!-- dnspod -->
      <section v-else-if="formState.provider === 4">
        <a-form-item
          label="Secret ID"
          field="provider_config.secret_id"
          hide-asterisk>
          <a-input
            v-model.trim="formState.provider_config.secret_id"
            placeholder="请输入 Secret ID"></a-input>
        </a-form-item>
        <a-form-item
          label="Secret Key"
          field="provider_config.secret_key"
          hide-asterisk>
          <a-input
            v-model.trim="formState.provider_config.secret_key"
            placeholder="请输入 Secret Key"></a-input>
        </a-form-item>
      </section>
      <!-- 独立版 -->
      <!--
      <section v-else>
        <a-form-item
          label="网关"
          field="provider_config.addr"
          hide-asterisk
          asterisk-position="end">
          <a-input
            v-model="formState.provider_config.addr"
            :max-length="200"
            placeholder="http(s)://example.com:8080" />
        </a-form-item>
        <a-form-item
          label="APP ID"
          field="provider_config.app_id"
          hide-asterisk
          asterisk-position="end">
          <a-input
            v-model="formState.provider_config.app_id"
            placeholder="请输入 APP ID" />
        </a-form-item>
        <a-form-item
          label="密钥"
          field="provider_config.app_key"
          hide-asterisk
          asterisk-position="end">
          <a-input
            v-model="formState.provider_config.app_key"
            placeholder="请输入密钥" />
        </a-form-item>
      </section>
      -->
    </a-form>
  </CloudDialog>
</template>
<script lang="ts" setup>
import type { DnsItem } from '@/apis/model/resolve'
import {
  addApiResolveDnsApiApi,
  updateApiResolveDnsApiApi
} from '@/apis/modules/resolve/dns'
import { providerOptions } from '@/constants'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import { cloneDeep, omit, pick } from 'lodash-es'

interface IProp {
  record?: DnsItem
}
const visible = defineModel<boolean>('visible', { required: true })

const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits(['reload', 'update:visible'])
const formRef = ref<FormInstance>()
const title = computed(() =>
  props.record?.id ? '编辑 DNS 账户' : '添加 DNS 账户'
)

const initialState = {
  name: '',
  provider: 2,
  provider_config: {
    // addr: '',
    // app_id: '',
    // app_key: '',
    api_token: '',
    access_key_id: '',
    access_key_secret: '',
    secret_id: '',
    secret_key: ''
  }
}

const formState = reactive(cloneDeep(initialState))
const rules = computed<Record<string, FieldRule[]>>(() => {
  return formState.provider === 1
    ? {
        name: { required: true, message: '请输入账户名称' },
        provider: { required: true, message: '请选择 DNS 服务商' },
        'provider_config.addr': {
          required: true,
          message: '请输入网关'
        },
        'provider_config.app_id': {
          required: true,
          message: '请输入 APP ID'
        },
        'provider_config.app_key': {
          required: true,
          message: '请输入密钥'
        }
      }
    : {
        name: { required: true, message: '请输入账户名称' },
        provider: { required: true, message: '请选择 DNS 服务商' },
        'provider_config.api_token': {
          required: true,
          message: '请输入 API TOKEN'
        },
        //3: aliyun
        'provider_config.access_key_id': [
          { required: true, message: '请输入 AccessKey ID', trigger: 'blur' }
        ],
        'provider_config.access_key_secret': [
          {
            required: true,
            message: '请输入 AccessKey Secret',
            trigger: 'blur'
          }
        ],
        //4: dnspod
        'provider_config.secret_id': [
          { required: true, message: '请输入 Secret ID', trigger: 'blur' }
        ],
        'provider_config.secret_key': [
          { required: true, message: '请输入 Secret Key', trigger: 'blur' }
        ]
      }
})
// const handleOpen = async () => {
//   await nextTick()
//   Object.assign(formState, props.record)
// }
const config_enum: Record<number, string[]> = {
  2: ['api_token'],
  3: ['access_key_id', 'access_key_secret'],
  4: ['secret_id', 'secret_key']
}
const handleSubmit = async () => {
  const error = await formRef.value?.validate()

  if (error) return false
  const conf = pick(formState.provider_config, config_enum[formState.provider])
  const data = {
    ...omit(formState, ['provider_config']),
    provider_config: conf
  }
  const fn = props.record?.id
    ? updateApiResolveDnsApiApi
    : addApiResolveDnsApiApi
  await fn(data).then(() => {
    ToastUtils.success('操作成功')
    visible.value = false
    emit('reload')
  })
}
watch(
  () => visible.value,
  async (v) => {
    await nextTick()
    if (v) {
      Object.assign(formState, cloneDeep(props.record))
    } else {
      await formRef.value?.resetFields()
      Object.assign(formState, cloneDeep(initialState))
    }
  }
)
</script>
<style lang="less" scoped>
.server-item {
  margin-bottom: 24px;
  :deep(.arco-form-item-label) {
    flex: 1;
  }
}
</style>
